package vip.indo.service.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.indo.entity.User;
import vip.indo.event.MyEvent;
import vip.indo.mapper.UserMapper;
import vip.indo.service.UserService;

import javax.annotation.Resource;
import java.sql.SQLException;

/**
 * @Author: tianlianyin
 * @Date: 2024/11/28 15:38
 * @Descripition:
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private ApplicationContext applicationContext;

    /**
     * 获取用户信息
     * @param username
     * @return
     */

    @Override
    public User getUserByName(String username) {
        return userMapper.getUserByName(username);
    }

    @Override
    @Transactional(rollbackFor = SQLException.class)//事务
    public void insertUser(User user) throws SQLException {
        // 插入用户信息
        userMapper.insertUser(user);
        //手动抛出异常
//        throw new RuntimeException("插入用户信息异常");
        throw new SQLException("数据库异常");
    }

    /**
     * 发布事件
     * @return
     */
    @Override
    public User getUserEvent() {
        User user=getUserByName("admin");
        //发布事件
        MyEvent myEvent=new MyEvent(this,user);
        applicationContext.publishEvent(myEvent);
        return user;
    }
}
